import { showNotification } from "./utils.js";
import { getProjectOwner, getProjectName, getProjectPath } from "./utils.js";
import http from './http-client.js';

// 活动类型数据 - 从API动态加载
let activityTypes = [];

// 加载活动类型配置
async function loadActivityTypes() {
    try {
        const response = await http.post('/api/projects', { api: 'get_activity_types' });
        activityTypes = response.data;
        console.log('活动类型配置加载成功:', activityTypes);
    } catch (error) {
        console.error('加载活动类型配置时发生错误:', error);
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', async function() {
    // 首先加载活动类型配置
    await loadActivityTypes();
    
    // 然后初始化其他组件
    initActivitySelector();
    setupWorkscopeEvents();
    setupActivityBlockEvents();
});

// 初始化活动选择对话框
function initActivitySelector() {
    /*********************************** 声明变量 ***********************************/
    const activitySelectorModal = document.getElementById('activitySelectorModal');
    const activitySearchInput = document.getElementById('activitySearchInput');
    const searchResultsContainer = document.getElementById('searchResultsContainer');
    const initialViewContainer = document.getElementById('initialViewContainer');
    const selectedCategoryTag = document.getElementById('selectedCategoryTag'); // 获取分类标签元素
    const selectedCategoryText = selectedCategoryTag.querySelector('.tag-text'); // 获取标签文本元素
    const selectedCategoryCloseBtn = selectedCategoryTag.querySelector('.btn-close'); // 获取标签关闭按钮
    // 监听添加活动按钮和添加workscope按钮点击事件，记录当前点击的按钮
    let currentAddButton = null;
    
    // 使用事件委托来监听动态生成的按钮
    document.addEventListener('click', function(event) {
        if (event.target.closest('.add-activity-btn') || event.target.closest('.add-workscope-btn')) {
            const btn = event.target.closest('.add-activity-btn') || event.target.closest('.add-workscope-btn');
            console.log('添加按钮被点击:', btn);
            currentAddButton = btn;
            // 确保模态框显示时保持currentAddButton的值
            const modal = new bootstrap.Modal(activitySelectorModal);
            modal.show();
        }
    });
    
    // 监听模态框显示事件，确保currentAddButton不会被意外清除
    activitySelectorModal.addEventListener('show.bs.modal', function(event) {
        // 如果不是通过添加按钮触发的，则保留currentAddButton的值
        if (!event.relatedTarget || 
            (!event.relatedTarget.classList.contains('add-activity-btn') && 
             !event.relatedTarget.classList.contains('add-workscope-btn'))) {
            return;
        }
        // 更新currentAddButton为触发模态框的按钮
        currentAddButton = event.relatedTarget;
    });
    
    // 监听模态框显示前事件，确保aria-hidden正确处理
    activitySelectorModal.addEventListener('show.bs.modal', function() {
        // 在模态框开始显示时就移除aria-hidden，避免焦点冲突
        activitySelectorModal.removeAttribute('aria-hidden');
    });
    
    // 监听模态框完全显示事件
    activitySelectorModal.addEventListener('shown.bs.modal', function() {
        // 确保搜索框获得焦点
        if (activitySearchInput) {
            activitySearchInput.focus();
        }
    });

    /*********************************** 辅助函数 ***********************************/
    // 搜索活动类型
    function searchActivities(query) {
        const results = activityTypes.filter(activity => 
            activity.title.toLowerCase().includes(query.toLowerCase())
        );
        
        renderSearchResults(results);
    }

    // 渲染搜索结果
    function renderSearchResults(results) {
        const activityList = searchResultsContainer.querySelector('.activity-list');
        activityList.innerHTML = '';
        
        if (results.length === 0) {
            activityList.innerHTML = '<div class="no-results">没有找到匹配的活动</div>';
            return;
        }
        
        results.forEach(activity => {
            const activityItem = document.createElement('div');
            activityItem.className = 'activity-item';
            activityItem.setAttribute('data-type', activity.name);
            activityItem.innerHTML = `
                <i class="bi ${activity.icon}"></i>
                <span>${activity.title}</span>
            `;
            
            activityItem.addEventListener('click', function() {
                newActivity(activity.name);
            });
            
            activityList.appendChild(activityItem);
        });
    }

    // 根据分类筛选活动
    function filterByCategory(category) {
        const results = activityTypes.filter(activity => activity.category === category);
        renderSearchResults(results);
        
        // 在搜索框中显示分类标签
        selectedCategoryText.textContent = category;
        selectedCategoryTag.classList.remove('d-none');
        activitySearchInput.classList.add('has-category-tag'); // 添加CSS类
        activitySearchInput.placeholder = ''; // 隐藏placeholder
        activitySearchInput.value = ''; // 清空搜索框内容
        activitySearchInput.focus(); // 聚焦搜索框
        
        // 显示搜索结果，隐藏初始视图
        searchResultsContainer.classList.remove('d-none');
        initialViewContainer.classList.add('d-none');
    }
    
    // 新的创建活动逻辑
    function newActivity(activityType) {
        if (currentAddButton) {
            // 获取项目信息
            const projectOwner = getProjectOwner();
            const projectName = getProjectName();
            // 获取测试用例名称
            const testName = document.querySelector('.flow-container').getAttribute('data-current-test');
            // 获取活动索引和位置信息
            const activityIndex = currentAddButton.getAttribute('data-position') || 0;
            const isInsideWorkscope = currentAddButton.getAttribute('data-inside-workscope') === 'true';
            const workscopeId = currentAddButton.getAttribute('data-workscope-id');
            
            // 判断是通过add-activity-btn还是add-workscope-btn触发的
            // const isAddWorkscopeBtn = currentAddButton.classList.contains('add-workscope-btn');
            
            // 显示加载指示器
            showNotification('正在创建活动...', 'info');
            
            // 先关闭模态框，避免焦点问题
            const modal = bootstrap.Modal.getInstance(activitySelectorModal);
            if (modal) {
                modal.hide();
            }
            
            // 通过add-workscope-btn触发，需要创建workscope并嵌入activity
            http.post('/api/projects', {
                    api: 'new_activity',
                    owner: projectOwner,
                    name: projectName,
                    test: testName,
                    id: workscopeId,
                    index: activityIndex,
                    typename: activityType,
                    inside: isInsideWorkscope,
                })
            .then(() => {
                // 重新加载测试用例数据
                openTestCase(testName);
                showNotification('活动创建成功', 'success');
            })
            .catch(error => {
                console.error('创建活动出错:', error);
                showNotification(error.message, 'error');
            });
        } else {
            showNotification('请先选择一个添加活动的位置', 'warning');
        }
    }
        
    // 重置模态框状态
    function resetModalState() {
        activitySearchInput.value = '';
        activitySearchInput.placeholder = '搜索活动...'; // 恢复placeholder
        selectedCategoryTag.classList.add('d-none'); // 隐藏分类标签
        activitySearchInput.classList.remove('has-category-tag'); // 移除CSS类
        searchResultsContainer.classList.add('d-none');
        initialViewContainer.classList.remove('d-none');
    }

    // 监听搜索输入框输入事件
    if (activitySearchInput) {
        activitySearchInput.addEventListener('input', function() {
            const query = this.value.trim();
            
            if (query === '') {
                // 如果搜索框为空，显示初始视图
                searchResultsContainer.classList.add('d-none');
                initialViewContainer.classList.remove('d-none');
            } else {
                // 否则显示搜索结果
                searchActivities(query);
                searchResultsContainer.classList.remove('d-none');
                initialViewContainer.classList.add('d-none');
            }
        });
        
        // 监听搜索输入框的keydown事件，处理退格删除标签
        activitySearchInput.addEventListener('keydown', function(event) {
            // 如果分类标签可见且按下的是退格键
            if (!selectedCategoryTag.classList.contains('d-none') && event.key === 'Backspace' && this.value === '') {
                // 阻止默认的退格行为
                event.preventDefault();
                // 触发分类标签的关闭按钮点击事件
                selectedCategoryCloseBtn.click();
            }
        });
    }
    /*********************************** 处理事件 ***********************************/
    // 监听活动项点击事件
    // 注意：这里的监听器是针对初始视图中的活动项，搜索结果中的活动项在渲染时单独添加监听器
    document.querySelectorAll('#initialViewContainer .activity-item').forEach(item => {
        item.addEventListener('click', function() {
            const activityType = this.getAttribute('data-type');
            newActivity(activityType);
        });
    });
    
    // 监听分类项点击事件
    document.querySelectorAll('.category-item').forEach(item => {
        item.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            filterByCategory(category);
        });
    });
    
    // 监听分类标签关闭按钮点击事件
    selectedCategoryCloseBtn.addEventListener('click', function() {
        resetModalState(); // 重置模态框状态，隐藏标签并显示初始视图
    });
    
    // 监听模态框开始关闭事件
    activitySelectorModal.addEventListener('hide.bs.modal', function() {
        // 在模态框开始关闭时立即移除所有焦点
        const focusedElement = activitySelectorModal.querySelector(':focus');
        if (focusedElement) {
            focusedElement.blur();
        }
        
        // 确保模态框本身也失去焦点
        if (document.activeElement === activitySelectorModal) {
            activitySelectorModal.blur();
        }
        
        // 将焦点转移到body或其他安全元素
        document.body.focus();
    });
    
    // 对话框完全关闭后重置状态
    activitySelectorModal.addEventListener('hidden.bs.modal', function() {
        // 延迟重置状态，确保模态框完全关闭
        setTimeout(() => {
            resetModalState();
        }, 100);
        
        // 确保移除所有可能残留的backdrop
        const backdrops = document.querySelectorAll('.modal-backdrop');
        backdrops.forEach(backdrop => {
            if (backdrop.parentNode) {
                backdrop.parentNode.removeChild(backdrop);
            }
        });
        
        // 恢复body的样式，防止页面保持灰色状态
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.body.style.paddingRight = '';
        
        // 重置currentAddButton
        currentAddButton = null;
        
        // 最后设置aria-hidden，此时应该没有焦点冲突
         setTimeout(() => {
             activitySelectorModal.setAttribute('aria-hidden', 'true');
         }, 50);
     });
}

/**
 * 进入设备桌面控件选择状态
 * @param {number} activityIndex - 活动索引
 * @param {string} workscopeId - 工作域ID
 * @param {string} deviceSn - 设备序列号
 * @param {jQuery} targetButton - 目标按钮元素
 */
function enterComponentSelectionMode(activityIndex, workscopeId, deviceSn, targetButton) {
    // 创建遮罩层，使除设备桌面以外的区域不可交互
    const overlay = $('<div class="component-selection-overlay"></div>');
    overlay.css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 9999,
        cursor: 'crosshair'
    });
    
    // 找到设备框架元素
    const deviceFrame = $('.device-frame');
    if (deviceFrame.length === 0) {
        showNotification('未找到设备桌面', 'error');
        return;
    }
    
    // 设置设备框架为可交互状态
    deviceFrame.css({
        position: 'relative',
        zIndex: 10000,
        pointerEvents: 'auto'
    });
    
    // 添加选择提示
    const selectionHint = $('<div class="selection-hint">点击设备桌面选择目标控件</div>');
    selectionHint.css({
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        backgroundColor: '#007bff',
        color: 'white',
        padding: '10px 20px',
        borderRadius: '5px',
        zIndex: 10001,
        fontSize: '14px',
        fontWeight: 'bold'
    });
    
    // 添加遮罩层和提示到页面
    $('body').append(overlay).append(selectionHint);
    
    // 监听设备桌面点击事件
    const deviceClickHandler = function(event) {
        event.preventDefault();
        event.stopPropagation();
        
        // 获取点击位置相对于设备框架的坐标
        const frameOffset = deviceFrame.offset();
        const frameWidth = deviceFrame.width();
        const frameHeight = deviceFrame.height();
        
        const clickX = event.pageX - frameOffset.left;
        const clickY = event.pageY - frameOffset.top;
        
        // 计算比例坐标
        const relativeX = clickX / frameWidth;
        const relativeY = clickY / frameHeight;
        
        console.log('设备桌面点击位置:', {
            absolute: { x: clickX, y: clickY },
            relative: { x: relativeX, y: relativeY },
            frame: { width: frameWidth, height: frameHeight }
        });
        
        // 退出选择状态
        exitComponentSelectionMode();
        
        // 调用后端API选择控件
        selectComponentAPI(deviceSn, relativeX, relativeY, activityIndex, workscopeId, targetButton);
    };
    
    // 绑定点击事件
    deviceFrame.on('click.componentSelection', deviceClickHandler);
    
    // 监听ESC键退出选择状态
    const escKeyHandler = function(event) {
        if (event.key === 'Escape') {
            exitComponentSelectionMode();
            $(document).off('keydown.componentSelection', escKeyHandler);
        }
    };
    $(document).on('keydown.componentSelection', escKeyHandler);
    
    // 点击遮罩层退出选择状态
    overlay.on('click', function() {
        exitComponentSelectionMode();
    });
}

/**
 * 退出设备桌面控件选择状态
 */
function exitComponentSelectionMode() {
    // 移除遮罩层和提示
    $('.component-selection-overlay').remove();
    $('.selection-hint').remove();
    
    // 恢复设备框架样式
    const deviceFrame = $('.device-frame');
    deviceFrame.css({
        position: '',
        zIndex: '',
        pointerEvents: ''
    });
    
    // 移除事件监听器
    deviceFrame.off('click.componentSelection');
    $(document).off('keydown.componentSelection');
}

/**
 * 调用后端API选择控件
 * @param {string} deviceSn - 设备序列号
 * @param {number} relativeX - 相对X坐标
 * @param {number} relativeY - 相对Y坐标
 * @param {number} activityIndex - 活动索引
 * @param {string} workscopeId - 工作域ID
 * @param {jQuery} targetButton - 目标按钮元素
 */
function selectComponentAPI(deviceSn, relativeX, relativeY, activityIndex, workscopeId, targetButton) {
    // 显示加载状态
    showNotification('正在选择控件...', 'info');
    
    // 获取当前项目和测试用例信息
    const projectPath = getProjectPath();
    const testName = document.querySelector('.flow-container').getAttribute('data-current-test');
    
    // 调用后端API
    http.post('/api/devices', {
        api: 'select_component',
        sn: deviceSn,
        projectPath: projectPath,
        testcaseName: testName,
        workscopeId: workscopeId,
        activityIndex: activityIndex,
        x: relativeX,
        y: relativeY,
    })
    .then(response => {
        if (response.data && response.data.imageUrl) {
            // 成功获取控件截图URL
            const imageUrl = response.data.imageUrl;
            console.log('控件选择成功，图片URL:', imageUrl);
            
            // 更新目标区域显示
            const targetSection = targetButton.closest('.target-section');
            const isAnchorBtn = targetButton.hasClass('indicate-anchor-btn');
            const altText = isAnchorBtn ? 'Anchor Element' : 'Target Element';
            const buttonClass = isAnchorBtn ? 'indicate-anchor-btn' : 'indicate-target-btn';
            const buttonTitle = isAnchorBtn ? '重新选择锚点' : '重新选择目标';
            
            targetSection.html(`
                <div class="target-display">
                    <img src="${imageUrl}" alt="${altText}" class="target-image" style="max-width: 100px; max-height: 100px; object-fit: contain;">
                    <button class="btn btn-sm btn-outline-secondary ${buttonClass}" title="${buttonTitle}"><i class="bi bi-cursor"></i></button>
                </div>
            `);
            
            showNotification('控件选择成功', 'success');
        } else {
            // API返回了错误信息
            const errorMessage = response.data?.message || '选择控件失败';
            showNotification(errorMessage, 'error');
        }
    })
    .catch(error => {
        console.error('选择控件API调用失败:', error);
        let errorMessage = '选择控件失败';
        
        if (error.response && error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message;
        } else if (error.message) {
            errorMessage = error.message;
        }
        
        showNotification(errorMessage, 'error');
    });
}

// 新的openTestCase实现
export function openTestCase(testName) {
    // 显示加载指示器
    const flowContainer = document.getElementById('flow-container');
    // 设置当前测试用例名称
    flowContainer.setAttribute('data-current-test', testName);
    flowContainer.innerHTML = '<div class="loading-indicator"><i class="bi bi-arrow-repeat spin"></i> 正在加载测试活动...</div>';
    
    // 发送UiTest请求获取测试活动数据
    const projectPath = getProjectPath();
    http.get(`/project/${projectPath}/${testName}`)
        .then(response => {
            // 渲染workscope和活动
            renderWorkscopes(flowContainer, response.data);
        })
        .catch(error => {
            console.error('加载测试活动出错:', error);
            flowContainer.innerHTML = `<div class="error-message"><i class="bi bi-exclamation-triangle"></i> 加载失败: ${error.message}</div>`;
        });
}

/**
 * 渲染workscope和活动到流程编辑器
 * @param {HTMLElement|Array} container - 容器元素
 * @param {Array} workscopes - workscope数据
 */
function renderWorkscopes(container, workscopes) {
    let html = '';
    workscopes.forEach((workscope, index) => {
        // 生成workscope HTML
        html += generateWorkscopeHtml(workscope, index);
        
        // 如果不是最后一个workscope，添加连接器
        if (index < workscopes.length - 1) {
            html += `
            <div class="workscope-connector">
                <div class="connector-line"></div>
                <button class="add-workscope-btn" data-bs-toggle="modal" data-bs-target="#activitySelectorModal" data-position="${index + 1}" data-inside-workscope="false"><i class="bi bi-plus"></i></button>
            </div>`;
        }
    });
    
    // 添加最后的添加workscope按钮
    html += `
    <div class="workscope-connector">
        <div class="connector-line"></div>
        <button class="add-workscope-btn" data-bs-toggle="modal" data-bs-target="#activitySelectorModal" data-position="${workscopes.length}" data-inside-workscope="false"><i class="bi bi-plus"></i></button>
    </div>`;
    
    container.innerHTML = html;
    
    // 事件监听已在初始化时设置，无需重复调用
}

/**
 * 生成workscope的HTML
 * @param {Object} workscope - workscope数据
 * @param {number} index - workscope索引
 * @returns {string} workscope HTML
 */
function generateWorkscopeHtml(workscope, index) {
    let activitiesHtml = '';
    
    // 生成workscope内部的activities
    if (workscope.activities && workscope.activities.length > 0) {
        // 在第一个activity之前添加连接器，允许在序列头部插入activity
        activitiesHtml += `
        <div class="activity-connector">
            <div class="connector-line"></div>
            <button class="add-activity-btn" data-bs-toggle="modal" data-bs-target="#activitySelectorModal" data-position="0" data-inside-workscope="true" data-workscope-id="${workscope.id}"><i class="bi bi-plus"></i></button>
        </div>`;
        
        workscope.activities.forEach((activity, actIndex) => {
            activitiesHtml += generateActivityBlockHtml(activity, `${index}-${actIndex}`, workscope.id);
            
            // 在每个activity之后添加连接器
            activitiesHtml += `
            <div class="activity-connector">
                <div class="connector-line"></div>
                <button class="add-activity-btn" data-bs-toggle="modal" data-bs-target="#activitySelectorModal" data-position="${actIndex + 1}" data-inside-workscope="true" data-workscope-id="${workscope.id}"><i class="bi bi-plus"></i></button>
            </div>`;
        });
    } else {
        // 如果workscope内没有activities，显示添加第一个activity的按钮
        activitiesHtml = `
        <div class="empty-workscope-message">
            <p>点击下方按钮添加第一个活动</p>
            <button class="add-activity-btn" data-bs-toggle="modal" data-bs-target="#activitySelectorModal" data-position="0" data-inside-workscope="true" data-workscope-id="${workscope.id}"><i class="bi bi-plus"></i></button>
        </div>`;
    }
    
    // 获取活动参数HTML
    const argsHtml = workscope.args_html;
    
    // 获取锚点HTML
    const properties = workscope.properties || {};
    const anchorHtml = properties.anchor_html;

    return `
    <div class="workscope-block" data-workscope-index="${index}" data-workscope-id="${workscope.id}">
        <div class="workscope-header">
            <span class="workscope-title">${workscope.title || 'Workscope'}</span>
            <div class="workscope-actions">
                <button class="btn btn-sm btn-link run-workscope-btn" title="执行"><i class="bi bi-play-fill"></i></button>
                <div class="dropdown">
                    <button class="btn btn-sm btn-link" data-bs-toggle="dropdown" aria-expanded="false" title="更多操作">
                        <i class="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item edit-workscope-btn" href="#">编辑</a></li>
                        <li><a class="dropdown-item duplicate-workscope-btn" href="#">复制</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-danger delete-workscope-btn" href="#">删除</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="workscope-body">
            <!-- Target选择 -->
            <div class="target-section">
                ${argsHtml}
            </div>
            
            <!-- 可折叠的额外属性 -->
            <div class="activity-properties">
                <div class="property-section">
                    <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#workscope-properties-${index}" aria-expanded="false">
                        <span>Properties</span>
                        <i class="bi bi-chevron-down"></i>
                    </div>
                </div>
                
                <div id="workscope-properties-${index}" class="collapse">
                    <!-- Anchor选择 -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#workscope-anchor-${index}" aria-expanded="false">
                            <span>Anchor</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="workscope-anchor-${index}" class="collapse">
                            <div class="property-content">
                                ${anchorHtml}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Device Selector -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#workscope-device-${index}" aria-expanded="false">
                            <span>Device</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="workscope-device-${index}" class="collapse">
                            <div class="property-content">
                                <div class="property-two-columns">
                                    <div class="property-row">
                                        <div class="property-label">Name</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm device-name" value="${properties.device?.name || ''}" placeholder="设备名称">
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Board</div>
                                        <div class="property-value">
                                            <select class="form-select form-select-sm device-board">
                                                <option value="">选择Board</option>
                                                <option value="board1" ${properties.device?.board === 'board1' ? 'selected' : ''}>Board 1</option>
                                                <option value="board2" ${properties.device?.board === 'board2' ? 'selected' : ''}>Board 2</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Product</div>
                                        <div class="property-value">
                                            <select class="form-select form-select-sm device-product">
                                                <option value="">选择Product</option>
                                                <option value="product1" ${properties.device?.product === 'product1' ? 'selected' : ''}>Product 1</option>
                                                <option value="product2" ${properties.device?.product === 'product2' ? 'selected' : ''}>Product 2</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Platform</div>
                                        <div class="property-value">
                                            <select class="form-select form-select-sm device-platform">
                                                <option value="">选择Platform</option>
                                                <option value="android" ${properties.device?.platform === 'android' ? 'selected' : ''}>Android</option>
                                                <option value="ios" ${properties.device?.platform === 'ios' ? 'selected' : ''}>iOS</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Version</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm device-version" value="${properties.device?.version || ''}" placeholder="版本号">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Timings -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#workscope-timings-${index}" aria-expanded="false">
                            <span>Timings</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="workscope-timings-${index}" class="collapse">
                            <div class="property-content">
                                <div class="property-two-columns">
                                    <div class="property-row">
                                        <div class="property-label">Delay Before</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm delay-before" value="${properties.timings?.delayBefore || '0.2'}">
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Delay After</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm delay-after" value="${properties.timings?.delayAfter || '0.3'}">
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Timeout</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm timeout" value="${properties.timings?.timeout || '30'}">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Options -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#workscope-action-options-${index}" aria-expanded="false">
                            <span>Options</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="workscope-action-options-${index}" class="collapse">
                            <div class="property-content">
                                ${properties?.options || ''}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Input/Output -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#workscope-input-output-${index}" aria-expanded="false">
                            <span>Input/Output</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="workscope-input-output-${index}" class="collapse">
                            <div class="property-content">
                                <div class="property-two-columns">
                                    <div class="property-row">
                                        <div class="property-label">Input</div>
                                        <div class="property-value">
                                            <textarea class="form-control form-control-sm input-field" rows="2" placeholder="输入数据">${properties.input || ''}</textarea>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Output</div>
                                        <div class="property-value">
                                            <textarea class="form-control form-control-sm output-field" rows="2" placeholder="输出数据">${properties.output || ''}</textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Activities序列 -->
            <div class="workscope-activities">
                ${activitiesHtml}
            </div>
        </div>
    </div>`;
}

/**
 * 生成活动块的HTML
 * @param {Object} activity - 活动数据
 * @param {string} index - 活动索引
 * @param {string} workscopeId - 所属workscope ID
 * @returns {string} 活动块HTML
 */
function generateActivityBlockHtml(activity, index, workscopeId) {
    // 获取活动参数HTML
    const argsHtml = activity.args_html;
    
    // 生成anchor按钮HTML
    const properties = activity.properties || {};
    const anchorHtml = properties.anchor_html;
    
    return `
    <div class="activity-block" data-activity-index="${index}" data-workscope-id="${workscopeId}">
        <div class="activity-header">
            <span class="activity-title">${activity.title}</span>
            <div class="activity-actions">
                <button class="btn btn-sm btn-link run-activity-btn" title="执行"><i class="bi bi-play-fill"></i></button>
                <div class="dropdown">
                    <button class="btn btn-sm btn-link" data-bs-toggle="dropdown" aria-expanded="false" title="更多操作">
                        <i class="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item edit-activity-btn" href="#">编辑</a></li>
                        <li><a class="dropdown-item duplicate-activity-btn" href="#">复制</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-danger delete-activity-btn" href="#">删除</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="activity-body">
            <!-- Target选择 -->
            <div class="target-section">
                ${argsHtml}
            </div>
            
            <!-- 可折叠的额外属性 -->
            <div class="activity-properties">
                <div class="property-section">
                    <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#properties-${index}" aria-expanded="false">
                        <span>Properties</span>
                        <i class="bi bi-chevron-down"></i>
                    </div>
                </div>
                
                <div id="properties-${index}" class="collapse">
                    <!-- Anchor选择 -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#anchor-${index}" aria-expanded="false">
                            <span>Anchor</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="anchor-${index}" class="collapse">
                            <div class="property-content">
                                ${anchorHtml}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Device Selector -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#device-${index}" aria-expanded="false">
                            <span>Device</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="device-${index}" class="collapse">
                            <div class="property-content">
                                <div class="property-two-columns">
                                    <div class="property-row">
                                        <div class="property-label">Name</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm device-name" value="${properties.device?.name || ''}" placeholder="设备名称">
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Board</div>
                                        <div class="property-value">
                                            <select class="form-select form-select-sm device-board">
                                                <option value="">选择Board</option>
                                                <option value="board1" ${properties.device?.board === 'board1' ? 'selected' : ''}>Board 1</option>
                                                <option value="board2" ${properties.device?.board === 'board2' ? 'selected' : ''}>Board 2</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Product</div>
                                        <div class="property-value">
                                            <select class="form-select form-select-sm device-product">
                                                <option value="">选择Product</option>
                                                <option value="product1" ${properties.device?.product === 'product1' ? 'selected' : ''}>Product 1</option>
                                                <option value="product2" ${properties.device?.product === 'product2' ? 'selected' : ''}>Product 2</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Platform</div>
                                        <div class="property-value">
                                            <select class="form-select form-select-sm device-platform">
                                                <option value="">选择Platform</option>
                                                <option value="android" ${properties.device?.platform === 'android' ? 'selected' : ''}>Android</option>
                                                <option value="ios" ${properties.device?.platform === 'ios' ? 'selected' : ''}>iOS</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Version</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm device-version" value="${properties.device?.version || ''}" placeholder="版本号">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Timings -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#timings-${index}" aria-expanded="false">
                            <span>Timings</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="timings-${index}" class="collapse">
                            <div class="property-content">
                                <div class="property-two-columns">
                                    <div class="property-row">
                                        <div class="property-label">Delay Before</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm delay-before" value="${properties.timings?.delayBefore || '0.2'}">
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Delay After</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm delay-after" value="${properties.timings?.delayAfter || '0.3'}">
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Timeout</div>
                                        <div class="property-value">
                                            <input type="text" class="form-control form-control-sm timeout" value="${properties.timings?.timeout || '30'}">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Options -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#action-options-${index}" aria-expanded="false">
                            <span>Options</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="action-options-${index}" class="collapse">
                            <div class="property-content">
                                ${properties?.options || ''}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Input/Output -->
                    <div class="property-section">
                        <div class="property-header collapsed" data-bs-toggle="collapse" data-bs-target="#input-output-${index}" aria-expanded="false">
                            <span>Input/Output</span>
                            <i class="bi bi-chevron-down"></i>
                        </div>
                        <div id="input-output-${index}" class="collapse">
                            <div class="property-content">
                                <div class="property-two-columns">
                                    <div class="property-row">
                                        <div class="property-label">Input</div>
                                        <div class="property-value">
                                            <textarea class="form-control form-control-sm input-field" rows="2" placeholder="输入数据">${properties.input || ''}</textarea>
                                        </div>
                                    </div>
                                    <div class="property-row">
                                        <div class="property-label">Output</div>
                                        <div class="property-value">
                                            <textarea class="form-control form-control-sm output-field" rows="2" placeholder="输出数据">${properties.output || ''}</textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>`;
}

/**
 * 设置workscope的事件监听
 */
// 全局事件监听器标记
let workscopeEventsSetup = false;

function setupWorkscopeEvents() {
    // 避免重复绑定事件监听器
    if (workscopeEventsSetup) {
        return;
    }
    workscopeEventsSetup = true;
    
    // 折叠/展开workscope - 使用和activity相同的逻辑
    $(document).on('click', '.workscope-header', function(e) {
        // 如果点击的是按钮，不触发折叠
        if ($(e.target).closest('button, .dropdown').length > 0) {
            return;
        }
        
        const workscopeBlock = $(this).closest('.workscope-block');
        const workscopeBody = workscopeBlock.find('.workscope-body');
        
        if (workscopeBody.is(':visible')) {
            workscopeBody.hide();
            workscopeBlock.addClass('collapsed');
        } else {
            workscopeBody.show();
            workscopeBlock.removeClass('collapsed');
        }
    });
    
    // 删除workscope
    $(document).on('click', '.delete-workscope-btn', function() {
        const workscopeBlock = $(this).closest('.workscope-block');
        const workscopeIndex = workscopeBlock.data('workscope-index');
        
        if (confirm('确定要删除这个Workscope吗？这将删除其中的所有活动。')) {
            // 删除workscope块和相关连接器
            const connector = workscopeBlock.next('.workscope-connector');
            if (connector.length > 0) {
                connector.remove();
            }
            workscopeBlock.remove();
            
            // 重新编号剩余的workscope
            $('.workscope-block').each(function(index) {
                $(this).attr('data-workscope-index', index);
            });
        }
    });
    
    // 编辑workscope
    $(document).on('click', '.edit-workscope-btn', function() {
        const workscopeBlock = $(this).closest('.workscope-block');
        const workscopeIndex = workscopeBlock.data('workscope-index');
        
        // TODO: 实现编辑workscope的逻辑
        console.log('编辑workscope:', workscopeIndex);
    });
    
    // 复制workscope
    $(document).on('click', '.duplicate-workscope-btn', function() {
        const workscopeBlock = $(this).closest('.workscope-block');
        const workscopeIndex = workscopeBlock.data('workscope-index');
        
        // TODO: 实现复制workscope的逻辑
        console.log('复制workscope:', workscopeIndex);
    });
    
    // 运行workscope
    $(document).on('click', '.run-workscope-btn', function() {
        const workscopeBlock = $(this).closest('.workscope-block');
        const workscopeId = workscopeBlock.data('workscope-id');
        
        // TODO: 实现运行workscope的逻辑
        console.log('运行workscope:', workscopeId);
    });
}

/**
 * 设置活动块的事件监听
 */
function setupActivityBlockEvents() {
    // 折叠/展开activity
    $(document).on('click', '.activity-header', function(e) {
        // 如果点击的是按钮，不触发折叠
        if ($(e.target).closest('button, .dropdown').length > 0) {
            return;
        }
        
        const activityBlock = $(this).closest('.activity-block');
        const activityBody = activityBlock.find('.activity-body');
        
        if (activityBody.is(':visible')) {
            activityBody.hide();
            activityBlock.addClass('collapsed');
        } else {
            activityBody.show();
            activityBlock.removeClass('collapsed');
        }
    });
    
    // Indicate Target按钮
    $(document).on('click', '.indicate-target-btn', function() {
        const activityBlock = $(this).closest('.activity-block');
        const activityIndex = activityBlock.data('activity-index');
        const workscopeId = activityBlock.data('workscope-id');
        
        // 检查是否选中了设备
        const deviceSelect = document.querySelector('.device-select');
        if (!deviceSelect || deviceSelect.value === '0' || !deviceSelect.value) {
            showNotification('请先选择一个设备', 'warning');
            return;
        }
        
        const selectedDeviceSn = deviceSelect.value;
        console.log('开始选择目标元素:', activityIndex, workscopeId, '设备SN:', selectedDeviceSn);
        
        // 进入设备桌面控件选择状态
        enterComponentSelectionMode(activityIndex, workscopeId, selectedDeviceSn, $(this));
    });
    
    // Indicate Anchor按钮
    $(document).on('click', '.indicate-anchor-btn', function() {
        const activityBlock = $(this).closest('.activity-block');
        const activityIndex = activityBlock.data('activity-index');
        const workscopeId = activityBlock.data('workscope-id');
        
        // 检查是否选中了设备
        const deviceSelect = document.querySelector('.device-select');
        if (!deviceSelect || deviceSelect.value === '0' || !deviceSelect.value) {
            showNotification('请先选择一个设备', 'warning');
            return;
        }
        
        const selectedDeviceSn = deviceSelect.value;
        console.log('开始选择目标元素:', activityIndex, workscopeId, '设备SN:', selectedDeviceSn);
        
        // 进入设备桌面控件选择状态
        enterComponentSelectionMode(activityIndex, workscopeId, selectedDeviceSn, $(this));
    });
    
    // 删除活动
    $(document).on('click', '.delete-activity-btn', function() {
        const activityBlock = $(this).closest('.activity-block');
        const activityIndex = activityBlock.data('activity-index');
        
        if (confirm('确定要删除这个活动吗？')) {
            // 删除活动块和相关连接器
            const connector = activityBlock.next('.activity-connector');
            if (connector.length > 0) {
                connector.remove();
            }
            activityBlock.remove();
            
            // 重新编号剩余的活动
            $('.activity-block').each(function(index) {
                $(this).attr('data-activity-index', index);
            });
        }
    });
    
    // 编辑活动
    $(document).on('click', '.edit-activity-btn', function() {
        const activityBlock = $(this).closest('.activity-block');
        const activityIndex = activityBlock.data('activity-index');
        
        // TODO: 实现编辑活动的逻辑
        console.log('编辑活动:', activityIndex);
    });
    
    // 复制活动
    $(document).on('click', '.duplicate-activity-btn', function() {
        const activityBlock = $(this).closest('.activity-block');
        const activityIndex = activityBlock.data('activity-index');
        
        // TODO: 实现复制活动的逻辑
        console.log('复制活动:', activityIndex);
    });
    
    // 运行活动
    $(document).on('click', '.run-activity-btn', function() {
        const activityBlock = $(this).closest('.activity-block');
        const activityIndex = activityBlock.data('activity-index');
        const workscopeId = activityBlock.data('workscope-id');
        
        // TODO: 实现运行活动的逻辑
        console.log('运行活动:', activityIndex, workscopeId);
    });
}